<?php

namespace App\Http\Controllers\Front;

use App\Common\Constant;
use App\Http\Controllers\Controller;
use App\Model\DistributionRewardErrorLog;
use App\Model\EnterpriseUserCommissionDetails;
use App\Model\UserCommissionDetail;
use App\Model\UserRecharge;
use App\Model\UserUp;
use App\User;


/**
 * 统一返佣 service层
 * 用户充值->1级会员返佣，2级会员返佣，1级业务员返佣，2级业务员返佣，3级业务员返佣，运营商返佣，城市合伙人返佣
 * Class UnifiedReturnCommissionController
 * @package App\Http\Controllers\Front
 */
class UnifiedReturnCommissionController extends Controller
{
    /**
     * @param $user_id 充值用户id
     * @param $out_trade_no 微信商户订单号
     * @throws \Exception
     * 逻辑思维：
     *      1判断用户类型
     *          1.1 类型=3
     *              2 该充值会员是业务员，给运营，城市提成
     *          1.2 类型=4
     *              3 该充值会员是会员
     *                  3.1 查询上级
     *                      3.1.1 上一级是业务员
     *                      3.1.2 上一级是会员
     *                          3.1.2.1 上二级是业务员
     *                          3.1.2.1 上二级是会员
     *                              3.1.2.1.1 三级会员
     */
    public function UnifiedReturnCommission($user_id, $out_trade_no){
        // 判断用户$user_id类型（3业务员，4会员）
        $userInfo = User::where('id', $user_id)->select("type", 'enterprise_user_id')->first();
        $rechargeObj = UserRecharge::where('out_trade_no', $out_trade_no)->where('is_pay', '1')->first();
        switch ($userInfo->type){
            case 3:
                $this->TypeSalesman($user_id, $rechargeObj);
                break;
            case 4:
                $this->TypeUser($user_id, $rechargeObj);
                break;
            default:
                break;
        }

        // 企业返佣
        if ($userInfo->enterprise_user_id) {
            $enterpriseUserCommissionDetails = new EnterpriseUserCommissionDetails();
            $enterpriseUserCommissionDetails->user_id = $user_id;
            $enterpriseUserCommissionDetails->relation_id = $userInfo->enterprise_user_id;
            $enterpriseUserCommissionDetails->proportion = Constant::ENTERPRISE_USER_PROPORTION;
            $enterpriseUserCommissionDetails->money = Constant::ENTERPRISE_USER_PROPORTION * $rechargeObj->money;
            $enterpriseUserCommissionDetails->status = 0;
            $enterpriseUserCommissionDetails->out_trade_no = $rechargeObj->out_trade_no;
            $enterprise_save = $enterpriseUserCommissionDetails->save();
            if ($enterprise_save == false) throw new \Exception('企业返佣 error');
        }
    }

    // 如果充值会员是业务员就只给【运营商返佣】，【城市合伙人】返佣
    public function TypeSalesman($user_id, $rechargeObj){
        $userInfo = User::where('id', $user_id)->select("operator_id", "place_partner_id")->first();
        if (!$rechargeObj) {
            throw new \Exception('没有查询到支付状态');
        }

        $userCommissionDetailsModel = new UserCommissionDetail();
        // 分销奖励错误日志
        $DistributionRewardErrorLog = new DistributionRewardErrorLog();

        if (!$userInfo->operator_id) { // 无运营商
            // 分销奖励错误日志
            $DistributionRewardErrorLog->error_id = $user_id;
            $DistributionRewardErrorLog->msg = $user_id . "本身是业务员但是没有运营商记录，请查询一下数据库";
            $DistributionRewardErrorLog->save();
            throw new \Exception('无运营商 error');
        }

        if (!$userInfo->place_partner_id) { // 无城市合伙人
            // 分销奖励错误日志
            $DistributionRewardErrorLog->error_id = $user_id;
            $DistributionRewardErrorLog->msg = $user_id . "本身是业务员但是没有城市合伙人记录，请查询一下数据库";
            $DistributionRewardErrorLog->save();
            throw new \Exception('无城市合伙人 error');
        }

        // 运营商返佣
        $add = $userCommissionDetailsModel->insertDetail(
            $user_id,
            $userInfo->operator_id,
            $rechargeObj->out_trade_no,
            '6',
            Constant::OPRATOR_PROPORTION,
            $rechargeObj->money * Constant::OPRATOR_PROPORTION
        );
        if ($add == false) throw new \Exception('运营商返佣添加 error');

        // 城市合伙人返佣
        $add = $userCommissionDetailsModel->insertDetail(
            $user_id,
            $userInfo->place_partner_id,
            $rechargeObj->out_trade_no,
            '7',
            Constant::PLACE_PARTNER_PROPORTION,
            $rechargeObj->money * Constant::PLACE_PARTNER_PROPORTION
        );
        if ($add == false) throw new \Exception('城市合伙人添加 error');
    }

    /**
     * 如果是会员就判断上级
     *      1上级无业务员
     *      2上级有业务员
     */
    public function TypeUser($user_id, $rechargeObj){
        $userInfo = User::where('id', $user_id)->select("salesman_id")->first();
        $user_up = UserUp::where("user_id", $user_id)->select("user_up_list")->first();
        if (!$user_up) throw new \Exception('上级表无用户存在 error');

        if ($user_up->user_up_list != 0) { // 有上级
            $user_arr = explode(",",$user_up->user_up_list);

            $ParentOneUserInfo = '';
            if (isset($user_arr[0]) && $user_arr[0] !=0) {
                $ParentOneUserInfo = User::where('id', $user_arr[0])->first(); // 上一级

            }

            $ParentTwoUserInfo = '';
            if (isset($user_arr[1]) && $user_arr[1] !=0) {
                $ParentTwoUserInfo = User::where('id', $user_arr[1])->first(); // 上二级
            }

            // 一级
            if($ParentOneUserInfo) {
                if ($ParentOneUserInfo->type == 3) { // 一级业务员提成，直接返回，因为不会有上级了
                    $this->ParentISalesman($user_id, $user_arr[0], 3, $rechargeObj);
                    return;
                }
                if ($ParentOneUserInfo->type == 4) { // 一级会员提成，不能返回，因为有可能有上级
                    $this->ParentIUser($user_id, $user_arr[0], 1, $rechargeObj);
                }
            }

            // 二级
            if ($ParentTwoUserInfo) {
                if ($ParentTwoUserInfo->type == 3) { //二级业务员提成
                    $this->ParentISalesman($user_id, $user_arr[1], 4, $rechargeObj);
                    return;
                }
                if ($ParentTwoUserInfo->type == 4) { //二级会员提成
                    $this->ParentIUser($user_id, $user_arr[1], 2, $rechargeObj);
                }
            }

            if ($userInfo->salesman_id > 0 && $userInfo->salesman_id != null) {
                // 三级业务员提成
                $this->ParentISalesman($user_id, $userInfo->salesman_id, 5, $rechargeObj);
            }
        }

    }

    // 业务员提成
    public function ParentISalesman($user_id, $salesman_id, $type, $rechargeObj){

        $userCommissionDetailsModel = new UserCommissionDetail();

        $proportion = '';
        $money = '';
        switch($type){
            case 3:
                $proportion = Constant::ONE_SALESMAN_PROPORTION;
                $money = $rechargeObj->money * Constant::ONE_SALESMAN_PROPORTION;
                break;
            case 4:
                $proportion = Constant::TWO_SALESMAN_PROPORTION;
                $money = $rechargeObj->money * Constant::TWO_SALESMAN_PROPORTION;
                break;
            case 5:
                $proportion = Constant::THREE_SALESMAN_PROPORTION;
                $money = $rechargeObj->money * Constant::THREE_SALESMAN_PROPORTION;
                break;
        }
        $add = $userCommissionDetailsModel->insertDetail(
            $user_id,
            $salesman_id,
            $rechargeObj->out_trade_no,
            $type,
            $proportion,
            $money
        );
        if ($add == false) throw new \Exception('二级业务员 error');

        // 给运营商和城市合伙人提成
        $this->TypeSalesman($user_id, $rechargeObj);
    }

    // 会员提成
    public function ParentIUser($user_id, $parent_user_id, $type, $rechargeObj){
        $userCommissionDetailsModel = new UserCommissionDetail();

        $proportion = '';
        $money = '';
        switch($type){
            case 1:
                $proportion = Constant::ONE_USER_PROPORTION;
                $money = $rechargeObj->money * Constant::ONE_USER_PROPORTION;
                break;
            case 2:
                $proportion = Constant::TWO_USER_PROPORTION;
                $money = $rechargeObj->money * Constant::TWO_USER_PROPORTION;
                break;
        }

        $add = $userCommissionDetailsModel->insertDetail(
            $user_id,
            $parent_user_id,
            $rechargeObj->out_trade_no,
            $type,
            $proportion,
            $money
        );
        if ($add == false) throw new \Exception($type . '级普通会员 error');
    }

    // 用法详细
//    public function TestURC(Request $request){
//
//        $user_id = $request->input("user_id");
//        $out = $request->input("out");
//        try{
//            \DB::beginTransaction();
//            $this->UnifiedReturnCommission($user_id, $out);
//            \DB::commit();
//        }catch (\Exception $e){
//            \DB::rollBack();
//            var_dump($e->getMessage());
//        }
//    }
}















